<template>
  <div class="bed-assignment-handle">
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="120px"
      v-loading="loading"
    >
      <el-form-item label="患者姓名">
        <span>{{ medicalRecord.userName }}</span>
      </el-form-item>
      
      <el-form-item label="科室">
        <span>{{ medicalRecord.departmentName }}</span>
      </el-form-item>
      
      <el-form-item label="病房" prop="wardId">
        <el-select
          v-model="form.wardId"
          placeholder="请选择病房"
          style="width: 100%"
          @change="handleWardChange"
          :loading="wardLoading"
        >
          <el-option
            v-for="ward in wardList"
            :key="ward.id"
            :label="ward.name"
            :value="ward.id"
          >
            <span>{{ ward.name }} ({{ ward.wardNo }})</span>
            <span style="float: right; color: #8492a6; font-size: 13px">
              {{ ward.occupiedBeds }}/{{ ward.totalBeds }}
            </span>
          </el-option>
        </el-select>
      </el-form-item>
      
      <el-form-item label="床位号" prop="bedNumber">
        <el-select
          v-model="form.bedNumber"
          placeholder="请选择床位"
          style="width: 100%"
          :disabled="!form.wardId"
        >
          <el-option
            v-for="bed in availableBeds"
            :key="bed"
            :label="bed + '号床'"
            :value="bed"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="预计住院天数" prop="estimatedDays">
        <el-input-number
          v-model="form.estimatedDays"
          :min="1"
          :max="30"
          style="width: 100%"
        />
      </el-form-item>
    </el-form>
    
    <div class="dialog-footer">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确定
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getWards } from '@/api/ward'
import { getAvailableBeds, assignBed } from '@/api/business'

// 定义props
const props = defineProps({
  medicalRecord: {
    type: Object,
    required: true
  }
})

// 定义emits
const emit = defineEmits(['close'])

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const wardLoading = ref(false)
const formRef = ref(null)
const wardList = ref([])
const availableBeds = ref([])

// 表单数据
const form = reactive({
  wardId: null,
  bedNumber: null,
  estimatedDays: 7
})

// 表单校验规则
const rules = {
  wardId: [
    { required: true, message: '请选择病房', trigger: 'change' }
  ],
  bedNumber: [
    { required: true, message: '请选择床位', trigger: 'change' }
  ],
  estimatedDays: [
    { required: true, message: '请输入预计住院天数', trigger: 'blur' }
  ]
}

// 获取病房列表
const fetchWards = async () => {
  try {
    wardLoading.value = true
    const response = await getWards()
    if (response.code === 200) {
      // 过滤出可用的病房
      wardList.value = response.data.filter(ward => 
        ward.status === 1 && ward.occupiedBeds < ward.totalBeds
      )
    }
  } catch (error) {
    console.error('获取病房列表失败:', error)
    ElMessage.error('获取病房列表失败')
  } finally {
    wardLoading.value = false
  }
}

// 病房选择改变时获取可用床位
const handleWardChange = async () => {
  if (!form.wardId) {
    availableBeds.value = []
    form.bedNumber = null
    return
  }
  
  try {
    loading.value = true
    const response = await getAvailableBeds(form.wardId)
    if (response.code === 200) {
      availableBeds.value = response.data
      form.bedNumber = null
    }
  } catch (error) {
    console.error('获取可用床位失败:', error)
    ElMessage.error('获取可用床位失败')
  } finally {
    loading.value = false
  }
}

// 处理取消
const handleCancel = () => {
  emit('close')
}

// 处理提交
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    const response = await assignBed({
      recordId: props.medicalRecord.id,
      wardId: form.wardId,
      bedNumber: form.bedNumber,
      estimatedDays: form.estimatedDays
    })
    
    if (response.code === 200) {
      ElMessage.success('床位分配成功')
      emit('close', 'success')
    } else {
      ElMessage.error(response.message || '床位分配失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('床位分配失败:', error)
      ElMessage.error('床位分配失败')
    }
  } finally {
    submitting.value = false
  }
}

// 组件挂载时获取病房列表
onMounted(() => {
  fetchWards()
})
</script>

<style scoped>
.bed-assignment-handle {
  padding: 20px 0;
}

.dialog-footer {
  margin-top: 20px;
  text-align: right;
}
</style> 